package com.sh.动态代理.handlker;

import com.sh.动态代理.transaction.DaoTransaction;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class TransactionHandler implements InvocationHandler{

    private DaoTransaction transaction;   // 增强类对象
    private Object obj;  // 目标类对象

    public TransactionHandler(DaoTransaction transaction, Object obj) {
        this.transaction = transaction;
        this.obj = obj;
    }

    /**
     * @param proxy  代理实例
     * @param method 代理方法
     * @param args   方法参数
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        if ( "save".equals(method.getName()) ) {
            transaction.before();
            result = method.invoke(obj,args);
            transaction.after();
        }else {
            result = method.invoke(obj,args);
        }
        return result;
    }

}
